package com.ruoyi.project.system.customer.service.impl;

import java.util.*;

import com.ruoyi.project.system.customer.vo.TaskCommentVo;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.system.user.service.IUserService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.system.customer.mapper.VeCustomerMapper;
import com.ruoyi.project.system.customer.domain.VeCustomer;
import com.ruoyi.project.system.customer.service.IVeCustomerService;
import com.ruoyi.common.utils.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 【请填写功能名称】Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-01-06
 */
@Service
public class VeCustomerServiceImpl implements IVeCustomerService 
{
    @Autowired
    private VeCustomerMapper veCustomerMapper;

    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private IUserService userService;

    /**
     * 查询【请填写功能名称】
     * 
     * @param CustomerID 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public VeCustomer selectVeCustomerByCustomerID(Long CustomerID)
    {
        return veCustomerMapper.selectVeCustomerByCustomerID(CustomerID);
    }

    /**
     * 查询【请填写功能名称】列表
     * 
     * @param veCustomer 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<VeCustomer> selectVeCustomerList(VeCustomer veCustomer)
    {
        return veCustomerMapper.selectVeCustomerList(veCustomer);
    }

    /**
     * 新增【请填写功能名称】
     * 
     * @param veCustomer 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertVeCustomer(VeCustomer veCustomer)
    {
        return veCustomerMapper.insertVeCustomer(veCustomer);
    }

    /**
     * 修改【请填写功能名称】
     * 
     * @param veCustomer 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateVeCustomer(VeCustomer veCustomer)
    {
        return veCustomerMapper.updateVeCustomer(veCustomer);
    }

    /**
     * 批量删除【请填写功能名称】
     * 
     * @param CustomerIDs 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteVeCustomerByCustomerIDs(String CustomerIDs)
    {
        return veCustomerMapper.deleteVeCustomerByCustomerIDs(Convert.toStrArray(CustomerIDs));
    }

    /**
     * 删除【请填写功能名称】信息
     * 
     * @param CustomerID 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteVeCustomerByCustomerID(Long CustomerID)
    {
        return veCustomerMapper.deleteVeCustomerByCustomerID(CustomerID);
    }

    @Override
    public List<VeCustomer> noFinishTask(Long userId, String processDefinitionKey) {
        List<VeCustomer> customerList = new ArrayList<>();
        // 创建一个任务查询对象
        TaskQuery taskQuery = taskService.createTaskQuery();
        // 办理人的任务列表
        List<Task> list = taskQuery
                .taskAssignee("" + userId)
                .processDefinitionKey(processDefinitionKey)
                .list();
        // 遍历任务列表
        if (list != null && list.size() > 0) {
            for (Task task : list) {
                if (!task.getName().equals("驾驶员出差申请")) {
                    Long flowInstanceId = Long.parseLong(task.getProcessInstanceId());
                    //根据流程id查询学生mapper的方法
                    VeCustomer customer = veCustomerMapper.selectVeCustomerByFlowInstanceID(flowInstanceId);
                    customerList.add(customer);
                }
            }
        }
        return customerList;
    }

    @Override
    public List<VeCustomer> finishTask(Long userId, String processDefinitionKey) {
        List<VeCustomer> listFinishCustomer = new ArrayList<>();

        List<HistoricTaskInstance> list = historyService
                .createHistoricTaskInstanceQuery()
                .taskAssignee(userId.toString())
                .processDefinitionKey(processDefinitionKey)
                .processFinished()
                .list();

        if (list != null && list.size() > 0) {
            for (HistoricTaskInstance temp : list) {
                if (!temp.getName().equals("驾驶员出差申请")) {
                    Long flowInstanceId = Long.parseLong(temp.getProcessInstanceId());
                    VeCustomer customer = veCustomerMapper.selectVeCustomerByFlowInstanceID(flowInstanceId);
                    listFinishCustomer.add(customer);
                }
            }
        }

        return new ArrayList<>(new HashSet<>(listFinishCustomer));
    }

    @Override
    @Transactional
    public int submit(Long id, Long userId) {
        VeCustomer customer = veCustomerMapper.selectVeCustomerByCustomerID(id);
        String processDefiKey = "travelrequest";
        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("inputUser1", userId);
        variables.put("inputUser2", 6);
        //没有启动这个流程
        if (customer.getStatus() == 0) {
            ProcessInstance pi = runtimeService.startProcessInstanceByKey(processDefiKey, variables);
            customer.setFlowInstanceId(Long.parseLong(pi.getProcessInstanceId()));
            customer.setStatus(2);//状态(0-未提交，1-打回，2-审核中，3-已完成）
            TaskQuery taskQuery = taskService.createTaskQuery();
            // 办理人的任务列表
            List<Task> list = taskQuery
                    .taskAssignee("" + userId)
                    .processInstanceId(pi.getProcessInstanceId())
                    .list();
            Task task = list.get(0);
            taskService.complete(task.getId());
            return veCustomerMapper.updateVeCustomer(customer);
        } else {//流程启动了，打回重新审批，就不用再启动流程
            Long flowInstanceId = customer.getFlowInstanceId();
            TaskQuery taskQuery = taskService.createTaskQuery();
            // 办理人的任务列表
            List<Task> list = taskQuery
                    .processInstanceId("" + flowInstanceId)
                    .list();
            Task task = list.get(0);
            taskService.complete(task.getId());
            customer.setStatus(2);//状态(0-未提交，1-打回，2-审核中，3-已完成）
            return veCustomerMapper.updateVeCustomer(customer);
        }
        /*VeCustomer customer = veCustomerMapper.selectVeCustomerByCustomerID(id);
        String processDefiKey = "travelrequest";
        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("inputUser1", userId);
        variables.put("inputUser2", 1);
        customer.setStatus(2);//状态(0-未提交，1-打回，2-审核中，3-已完成）
        ProcessInstance pi = runtimeService.startProcessInstanceByKey(processDefiKey, variables);
        customer.setFlowInstanceId(Long.parseLong(pi.getProcessInstanceId()));

        TaskQuery taskQuery = taskService.createTaskQuery();
        List<Task> list = taskQuery
                .taskAssignee("" + userId)
                .processInstanceId(pi.getProcessInstanceId())
                .list();
        Task task = list.get(0);
        taskService.complete(task.getId());

        return veCustomerMapper.updateVeCustomer(customer);*/
    }

    @Override
    @Transactional
    public void completeTask(Long flowInstanceId, Integer agree, Long userId, String comment, Long id) {
        TaskQuery taskQuery = taskService.createTaskQuery();
        // 办理人的任务列表
        List<Task> list = taskQuery
                .processInstanceId("" + flowInstanceId)
                .list();

        // 遍历任务列表
        Map<String, Object> params = new HashMap<String, Object>();
        VeCustomer customer = veCustomerMapper.selectVeCustomerByCustomerID(id);
        if (list != null && list.size() > 0) {
            for (Task task : list) {
                if (task.getName().equals("部门主管审批")) {
                    if (agree == 1) {
                        params.put("inputUser3", 7);
                        customer.setStatus(2);//状态(0-未提交，1-打回，2-审核中，3-已完成）
                    } else {
                        customer.setStatus(1);
                    }
                    params.put("pass1", agree);
                } else {
                    params.put("pass2", agree);
                    if (agree == 1) {
                        customer.setStatus(3);
                    } else {
                        customer.setStatus(1);
                    }
                }

                veCustomerMapper.updateVeCustomer(customer);

                // 添加批注时候的审核人，通常应该从session获取
                Authentication.setAuthenticatedUserId(userId.toString());

                // 添加批注
                taskService.addComment(task.getId(), task.getProcessInstanceId(), comment);

                // taskId：任务id
                taskService.complete(task.getId(), params);
            }
        }
    }
    @Override
    public List<TaskCommentVo> getTaskCommentList(Long flowInstanceId) {
        List<TaskCommentVo> taskCommentVoList = new ArrayList<>();
        List<Comment> list = new ArrayList();

        //从历史批注中取数据
        list = taskService.getProcessInstanceComments("" + flowInstanceId);
        for (Comment com : list) {
            TaskCommentVo taskCommentVo = new TaskCommentVo();
            taskCommentVo.setMessage(com.getFullMessage());
            User user = userService.selectUserById(Long.parseLong(com.getUserId()));
            taskCommentVo.setUserName(user.getUserName());

            //从历史任务取数据
            List<HistoricTaskInstance> hist = historyService.createHistoricTaskInstanceQuery()
                    .processInstanceId("" + flowInstanceId)
                    .taskId(com.getTaskId())
                    .list();
            if (hist != null && hist.size() > 0) {
                HistoricTaskInstance historicTaskInstance = hist.get(0);
                taskCommentVo.setTaskKeyId(historicTaskInstance.getTaskDefinitionKey());
                taskCommentVo.setTaskName(historicTaskInstance.getName());
            }
            taskCommentVoList.add(taskCommentVo);
        }

        //排序
        List<TaskCommentVo> taskCommentVoListSort = new ArrayList<>();
        for (int i = taskCommentVoList.size() - 1; i >= 0; i--) {
            TaskCommentVo temp = taskCommentVoList.get(i);
            taskCommentVoListSort.add(temp);
        }
        return taskCommentVoListSort;
    }
}
